import {useEffect, useState} from 'react'
import {Image, Input, Text, View} from '@tarojs/components'
import Taro from '@tarojs/taro'
import './index.scss'
import userInfo from "@/store/user";
import user from "@/store/user";
import http from "@/request";
import {Swiper, Button} from "@taroify/core";
import Avatar from "@/components/avatar";
import config from "@/request/config";
import {ShowLoading, ShowToast, ToPage} from "@/utils";

let recyclingTime = 30
export default function PersonalPage() {
    // 修改用户名相关状态
    const [showUsernameModal, setShowUsernameModal] = useState(false)
    const [showPasswordModal, setShowPasswordModal] = useState(false)
    const [newUsername, setNewUsername] = useState('')
    const [userPassConfig, setUserPassConfig] = useState({
        confirmPassword: '',
        newPassword: '',
        oldPassword: ''
    })
    const [imgs, setImgs] = useState<{relativePath: string}[]>([])

    // 显示修改用户名模态框
    const showEditUsernameModal = () => {
        setNewUsername(userInfo.info?.username || '')
        setShowUsernameModal(true)
    }

    // 隐藏修改用户名模态框
    const hideEditUsernameModal = () => {
        setShowUsernameModal(false)
    }

    // 保存用户名
    const saveUsername = () => {
        if (!newUsername.trim()) {
            Taro.showToast({
                title: '用户名不能为空',
                icon: 'none'
            })
            return
        }
        userInfo.updateInfo()
        Taro.showToast({
            title: '修改成功',
            icon: 'success'
        })
        hideEditUsernameModal()
    }

    // 跳转到密码设置页面
    const navigateToPasswordSetting = () => {
        setUserPassConfig({
            confirmPassword: '',
            newPassword: '',
            oldPassword: ''
        })
        console.log(123)
        setShowPasswordModal(true)
    }

    // 退出登录
    const logout = () => {
        Taro.showModal({
            title: '提示',
            content: '确定要退出登录吗？',
            success: (res) => {
                if (res.confirm) {
                    http.get('/disp/wx/system/logout').finally(() => {
                        user.updateInfo({})
                        ToPage('/pages/login/index')
                    }).finally(() => {
                        Taro.showToast({
                            title: '已退出登录',
                            icon: 'success'
                        })
                    })
                }
            }
        })
    }

    const getConfig = () => {
        http.get('/disp/biz/globalCfg/getDefault').then(res => {
            setImgs(JSON.parse(res.data.personalBackgroundImage) || [])
            recyclingTime = res.data.recyclingTime
        }).catch(() => {
            ShowToast('获取配置失败')
        })
    }
    useEffect(() => {
        getConfig()
    }, []);

    const preview = (index) => {
        Taro.previewImage({
            urls: imgs.map(item => config.BASE_URL + item.relativePath),
            current: index
        })
    }

    const setUserPassConfigItem = (val: string, key: string) => {
        setUserPassConfig((data) => {
            return {
                ...data,
                [key]: val
            }
        })
    }
    const saveUserPassword = () => {
        ShowLoading()
        http.post('/disp/sys/user/updatePassword', {
            ...userPassConfig,
            userCode: userInfo.info?.userCode,
        }).then(() => {
            ShowToast('修改成功')
            setShowPasswordModal(false)
        }).catch((err) => {
            ShowToast(err.msg || '修改失败')
        })
    }
    const hideEditPasswordModal = () => {
        setShowPasswordModal(false)
    }

    return (
        <View className='personal-container'>
            {/* 顶部轮播图 */}

            <Swiper className="basic-swiper" autoplay={recyclingTime * 1000}>
                <Swiper.Indicator />
                {
                    (imgs || []).map((img, i) => {
                        return (<Swiper.Item className={'switch-item'} key={i}>
                            <Image className="image" mode={"aspectFill"} onClick={() => preview(i)} src={config.BASE_URL + img.relativePath} />
                            {/*<View className={'notic-text'}>美方宣布对华征收125%关税 中国外交部回应 中新网北京4月10日电 (记者 张素)中国外交部发言人林剑4月10日主持例行记者会。会上，有记者就美方宣布对中方征收125%关税一事</View>*/}
                        </Swiper.Item>)
                    })
                }
            </Swiper>

            {/* 用户信息区域 */}
            <View className='user-info'>
                <View className='avatar-section'>
                    <Avatar className="avatar-comp" size={'40px'} url={userInfo.info?.headImage}></Avatar>
                    <View className='username-section flex-row'>
                        <Text className='username flex1'>
                            {userInfo.info?.username}
                        </Text>
                        {/*<Text className='edit-btn iconfont icon-base-edit2' onClick={showEditUsernameModal}/>*/}
                    </View>
                </View>
            </View>

            {/* 功能列表 */}
            <View className='function-list'>
                <View className='function-item' onClick={navigateToPasswordSetting}>
                    <Text className='function-icon'>🔒</Text>
                    <Text className='function-text'>密码设置</Text>
                    <Text className='arrow iconfont icon-base-right'/>
                </View>
                <View className='function-item' onClick={logout}>
                    <Text className='function-icon'>🚪</Text>
                    <Text className='function-text'>退出登录</Text>
                    <Text className='arrow iconfont icon-base-right'/>
                </View>
            </View>

            {showUsernameModal && (
                <View className='modal-mask'>
                    <View className='modal-container'>
                        <View className='modal-header'>
                            <Text className='modal-title'>修改用户名</Text>
                        </View>
                        <View className='modal-content'>
                            <Input
                                type='text'
                                placeholder='请输入新用户名'
                                value={newUsername}
                                onInput={(e) => setNewUsername(e.detail.value)}
                                className='username-input'
                            />
                        </View>
                        <View className='modal-footer'>
                            <Button className='modal-button cancel' onClick={hideEditUsernameModal}>
                                取消
                            </Button>
                            <Button color="primary" className='modal-button confirm' onClick={saveUsername}>
                                保存
                            </Button>
                        </View>
                    </View>
                </View>
            )}

            {showPasswordModal && (
                <View className='modal-mask'>
                    <View className='modal-container'>
                        <View className='modal-header'>
                            <Text className='modal-title'>修改用户密码</Text>
                        </View>
                        <View className='modal-content'>
                            <Input
                                type='password'
                                placeholder='请输入旧密码'
                                value={userPassConfig.oldPassword}
                                onInput={(e) => setUserPassConfigItem(e.detail.value, 'oldPassword')}
                                className='username-input'
                            />
                            <Input
                                type='password'
                                placeholder='请输入新密码'
                                value={userPassConfig.newPassword}
                                onInput={(e) => setUserPassConfigItem(e.detail.value, 'newPassword')}
                                className='username-input'
                            />
                            <Input
                                type='password'
                                placeholder='请再次输入新密码'
                                value={userPassConfig.confirmPassword}
                                onInput={(e) => setUserPassConfigItem(e.detail.value, 'confirmPassword')}
                                className='username-input'
                            />
                        </View>
                        <View className='modal-footer'>
                            <Button className='modal-button cancel' onClick={hideEditPasswordModal}>
                                取消
                            </Button>
                            <Button color="primary" className='modal-button confirm' onClick={saveUserPassword}>
                                保存
                            </Button>
                        </View>
                    </View>
                </View>
            )}
        </View>
    )
}